const WebSocketClient = require('websocket').client
const { wsFeature, noOrderFeature } = require('../assets/js/wsFeature')
const formatOrder = require('../assets/js/OrderFormat')
const config = require('../assets/config/conf')
const middle = require('../assets/js/middle')
const submit = require('../assets/js/submit')
const holy_pressure_data = require('../assets/data/holyPressureData.json')


var client = new WebSocketClient()

const url = `${config.urlBase}${config.createApi}?verifyKey=${config.verifyKey}&qq=${config.qq}`

client.on('connectFailed', function (error) {
    console.log('Connect Error: ' + error.toString())
})

client.on('connect', connection => {
    var session
    console.log('WebSocket Client Connected')
    connection.on('error', function (error) {
        console.log("Connection Error: " + error.toString())
    })
    connection.on('close', function () {
        console.log('echo-protocol Connection Closed')
    })
    connection.on('message', e => {

        // wsReceive(e)
        console.log(e)
        let data = JSON.parse(e.utf8Data).data
        // 判断第一次连接ws
        if (data && data.session) {
            session = data.session
        }
        let text = ''
        let qq_groups = config.groups
        let group = ''
        let qq = ''
        if (data && data.type && data.type == "GroupMessage") {
            if (qq_groups.indexOf(data.sender.group.id.toString()) == -1) return
            group = data.sender.group.id
            qq = data.sender.id

            data.messageChain.forEach(msg => {
                if (msg.type == 'Plain') {
                    text = msg.text
                }
            })
            if (middle.sessions.findIndex(p => p.session == `${group}_${qq}`) != -1) {
                let session = middle.sessions.find(p => p.session == `${group}_${qq}`)
                submit({
                    order: session.order,
                    msgFormat: text,
                    group: group,
                    qq: qq
                })
                return
            }
        }
        let msgFormat = text.split(' ')
        let order = formatOrder.find(p => msgFormat[0] == p.order)
        // 神罚
        if (holy_pressure_data[qq]) {
            noOrderFeature({
                order: { reply: '脑瘫' },
                msgFormat: text,
                group,
                qq
            })
            return
        }
        if (order) {
            // 参数：匹配到指令对象，格式化的消息，群组名称，
            // 指令对象包含：指令，回复的消息，绑定的函数名称（暂定这么多，之后可能还会加报错息）
            wsFeature({ order, msgFormat, group, qq })
        }


    })

    exports.sendWSPush = message => {
        if (!connection.connected) {
            console.log('websocket已断开')
            // 在这里可以尝试重连
        }
        else {
            // 将所有消息发送携带session
            // 用浏览器sessionStorage的方式保存缓存
            if (session) {
                message.content.sessionKey = session
            }
            else {
                console.log('没有可用websocket会话，将跳转到登录页重新连接！')
                return
            }
            connection.sendUTF(JSON.stringify(message))
        }
    }
    // sendNumber();


})


exports.linkStart = () => client.connect(url);

